<?php

namespace yunj\app\admin\model;

use think\model\Collection;
use yunj\app\admin\enum\State;
use yunj\app\admin\service\auth\AuthService;

class AdminMember extends Model {

    // 定义与角色表的多对多关联
    public function roles() {
        // 中间表使用表名，使用模型名需继承 think\model\Pivot 导致中间表模型不能实例化
        return $this->belongsToMany(AdminMemberRole::class, 'admin_member_role_relation', 'role_id', 'member_id');
    }

    // 判断当前成员是否拥有全部权限
    public function isHasAllAuth(): bool {
        if (isset($this->isHasAllAuth)) {
            return $this->isHasAllAuth;
        }
        $isHasAllAuth = false;
        if ($this->pid == 0) {
            $isHasAllAuth = true;
        } else {
            foreach ($this->roles as $role) {
                /** @var AdminMemberRole $role */
                if (in_array($role->alias, AuthService::HAS_ALL_AUTH_ROLES, true)) {
                    $isHasAllAuth = true;
                    break;
                }
            }
        }
        $this->isHasAllAuth = $isHasAllAuth;
        return $isHasAllAuth;
    }

    /**
     * 获取当前成员拥有的角色
     * @return Collection
     */
    public function getOwnRoles() {
        /** @var Collection $roles */
        $roles = $this->roles;
        return $roles->where('state', State::NORMAL);
    }

    /**
     * 获取当前成员拥有的全部权限
     * @return array
     */
    public function getOwnAllAuths(): array {
        if (isset($this->ownAuths)) {
            return $this->ownAuths;
        }

        $ownAuths = [];
        if ($this->isHasAllAuth()) {
            $ownAuths = array_keys(AuthService::getInstance()->getAllAuths());
        } else {
            $roles = $this->getOwnRoles();
            foreach ($roles as $role) {
                /** @var AdminMemberRole $role */
                if ($role->auths) {
                    $ownAuths = array_merge($ownAuths, $role->getAuthsToArray());
                }
            }
            $ownAuths = array_unique($ownAuths);
        }
        $this->ownAuths = $ownAuths;
        return $ownAuths;
    }

}